package com.link2room.rodimus.service.impl;

import com.link2room.common.constant.DefaultValue;
import com.link2room.common.dao.ICommonDao;
import com.link2room.common.dto.result.base.MemberSessionDto;
import com.link2room.common.dto.threadlocal.ApiThreadLocal;
import com.link2room.common.enums.BaseSysExceptionEnum;
import com.link2room.common.exception.SysException;
import com.link2room.common.jpa.condition.ConditionDetail;
import com.link2room.common.jpa.condition.L2RCondition;
import com.link2room.common.jpa.criteria.CriteriaUtil;
import com.link2room.common.jpa.result.QueryResult;
import com.link2room.common.mns.MNSUtil;
import com.link2room.common.service.ICommonService;
import com.link2room.common.util.*;
import com.link2room.rodimus.constant.CouponConstant;
import com.link2room.rodimus.constant.CouponConsumeConstant;
import com.link2room.rodimus.dto.param.api.CouponConsumeParamDto;
import com.link2room.rodimus.dto.param.api.CouponPresentResetParamDto;
import com.link2room.rodimus.dto.result.base.CouponConsumeDto;
import com.link2room.rodimus.dto.result.base.CouponConsumeTempDto;
import com.link2room.rodimus.entity.*;
import com.link2room.rodimus.service.ICouponService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;

import static com.link2room.enums.exception.RodimusSysExceptionEnum.COUPON_ERROR;
import static com.link2room.rodimus.constant.CouponConstant.PRESENT_RESET_DELAY;
import static com.link2room.rodimus.constant.RodimusMnsConstant.QUEUE_RESET_PRESENT_COUPON;

/**
 * Created by LN on 2017/7/24.10:37
 */
@Component("couponService")
public class CouponServiceImpl implements ICouponService {
    @Autowired
    private RedisLockRegistry couponNoLock;

    @Resource
    private ICommonService commonService;

    @Resource
    private ICommonDao commonDao;

    @Resource
    private MNSUtil mnsUtil;

    private static String couponNoLocLkey = "cou_no";

    private static String couponPresendLocLkey = "cou_pno";

    private static String couponConsumLocLkey = "cou_cons";

    @Override
    public List<CouponDetailEntity> createNewCouponDetail(String orderNo , String lhotelGroupCode , String couponCode, String openid, Integer num ,String saleType,String memberNo) {
        L2RAssert.numberNull(num, "[num] is null.");
        L2RAssert.stringBlank(couponCode,"[couponCode] is null.");
        L2RAssert.stringBlank(openid,"[openid] is null.");
        Date now = new Date();
        List<CouponDetailEntity> list = new ArrayList<>();
        for (int i = 0; i < num; i++){
            CouponDetailEntity newEntity = new CouponDetailEntity();
            newEntity.setLhotelGroupCode(lhotelGroupCode);
            newEntity.setOwnDate(now);
            newEntity.setSta(CouponConstant.COUPON_STA.VALID);
            newEntity.setOpenid(openid);
            newEntity.setCouponCode(couponCode);
            newEntity.setMemberNo(memberNo);
            try {
                newEntity.setCouponNo(this.generateNewCouponNo());
            } catch (Exception e) {
                throw new SysException(BaseSysExceptionEnum.BASE_FUCATION_OPTION,e);
            }
            newEntity.setSaleType(saleType);
            newEntity.setOrderNo(orderNo);
            list.add(newEntity);
        }
        return list;
    }

    @Override
    public String generateNewCouponNo() throws Exception {
        return callProcedure(couponNoLocLkey);
    }

    @Override
    public String generateCouponPresentNo() throws Exception {
        return callProcedure(couponPresendLocLkey);
    }

    @Override
    @Transactional
    public void savePresent(CouponPresentBaseEntity presentBaseEentity, List<CouponPresentDetailEntity> cpdList, List<CouponDetailEntity> couponDetailEntitys) throws Exception {
        commonDao.save(presentBaseEentity);
        commonDao.saveList(cpdList);
        commonDao.mergeList(couponDetailEntitys);
        this.sendResetPresentCouponMsg(presentBaseEentity.getPresentNo());
    }

    @Override
    public String couponSign(String opennid, String couponPresentNo) {
        return MD5Util.getMd5_32(opennid + couponPresentNo);
    }

    @Override
    public void checkCouponPresent(String presentNo, String couponSign, String toUser) throws Exception {
        CouponPresentBaseEntity find = new CouponPresentBaseEntity();
        find.setPresentNo(presentNo);
        CouponPresentBaseEntity qres = commonDao.findOne(CouponPresentBaseEntity.class, CriteriaUtil.getCriteriaAllEQ(find));
        L2RAssert.isTrue(qres == null, new SysException(COUPON_ERROR, "分享不存在"));
        L2RAssert.isTrue(!this.couponSign(qres.getOpenid(), presentNo).equals(couponSign), new SysException(COUPON_ERROR, "无效分享,签名错误."));
        L2RAssert.isTrue(CouponConstant.PRESEND_STA.STA_OVERDUE.equals(qres.getSta()), new SysException(COUPON_ERROR, "赠送已过期"));
        L2RAssert.isTrue(new Date().after(qres.getGiveEndDate()), new SysException(COUPON_ERROR, "赠送已过期"));
        L2RAssert.isTrue(CouponConstant.PRESEND_STA.STA_GIVEN.equals(qres.getSta()), new SysException(COUPON_ERROR, "已经领取完毕"));
        L2RAssert.isTrue(qres.getReceivedNum() >= qres.getNumPerPart() * qres.getPartsNum(), new SysException(COUPON_ERROR, "已经领取完毕"));
        L2RAssert.isTrue(hasPresentDrew(toUser, presentNo), new SysException(COUPON_ERROR, "你已经领取过了。"));

    }

    @Override
    @Transactional
    public void doDraw(String presentNo, String toUser, String remark) throws Exception {
        Lock lock = couponNoLock.obtain(presentNo);
        if (lock.tryLock(5, TimeUnit.SECONDS)) {
            try {
                CouponPresentBaseEntity find = new CouponPresentBaseEntity();
                find.setPresentNo(presentNo);
                CouponPresentBaseEntity qres = commonDao.findOne(CouponPresentBaseEntity.class, CriteriaUtil.getCriteriaAllEQ(find));
                L2RAssert.isTrue(qres == null, new SysException(COUPON_ERROR, "分享不存在"));
                L2RAssert.isTrue(CouponConstant.PRESEND_STA.STA_OVERDUE.equals(qres.getSta()), new SysException(COUPON_ERROR, "赠送已过期"));
                L2RAssert.isTrue(new Date().after(qres.getGiveEndDate()), new SysException(COUPON_ERROR, "赠送已过期"));
                L2RAssert.isTrue(CouponConstant.PRESEND_STA.STA_GIVEN.equals(qres.getSta()), new SysException(COUPON_ERROR, "已经领取完毕"));
                L2RAssert.isTrue(qres.getReceivedNum() >= qres.getPartsNum(), new SysException(COUPON_ERROR, "已经领取完毕"));
                L2RAssert.isTrue(hasPresentDrew(toUser, presentNo), new SysException(COUPON_ERROR, "你已经领取过了。"));
                //领券
                List<CouponPresentDetailEntity> presentDetails = findGivingCoupon(presentNo, qres.getNumPerPart());
                L2RAssert.isTrue(CollectionUtils.isEmpty(presentDetails) || presentDetails.size() < qres.getNumPerPart(), new SysException(COUPON_ERROR, "已领取完毕。"));
                List<CouponDetailEntity> updateCoupons = new ArrayList<>();
                presentDetails.forEach(entity -> {
                    CouponDetailEntity newCoupon = this.initNewCoupon(entity.getCouponCode(), qres.getLhotelGroupCode(), toUser, CouponConstant.SALE_TYPE.PRESENT, qres.getOpenid());
                    updateCoupons.add(newCoupon);
                    entity.setNewCouponNo(newCoupon.getCouponNo());
                    entity.setToUser(toUser);
                    entity.setOwnDate(new Date());
                    entity.setRemark(remark);
                    entity.setNewCouponNo(newCoupon.getCouponNo());
                    entity.setIsPresend(DefaultValue.T);
                });

                //查找被分享的券
                List<CouponDetailEntity> oldCoupnos = findCouponByNo(presentDetails.stream().map(CouponPresentDetailEntity::getCouponNo).collect(Collectors.toList()));
                oldCoupnos.stream().forEach(couponDetailEntity -> {
                    couponDetailEntity.setSta(CouponConstant.COUPON_STA.GAVE);
                    updateCoupons.add(couponDetailEntity);
                });
                qres.setReceivedNum(qres.getReceivedNum() + 1);
                if (qres.getReceivedNum() >= qres.getPartsNum()) {
                    qres.setSta(CouponConstant.PRESEND_STA.STA_GIVEN);
                }

                commonDao.merge(qres);
                commonDao.saveOrMergeList(updateCoupons);
                commonDao.mergeList(presentDetails);

            } finally {
                lock.unlock();
            }


        } else {
            throw new SysException(COUPON_ERROR, "抢券人数太多,稍后重试.");
        }
    }


    private List<CouponDetailEntity> findCouponByNo(List<String> couponList) throws Exception {
        L2RCondition condition = new L2RCondition();
        condition.setAndConditions(new ConditionDetail[]{
                new ConditionDetail(CouponDetailEntity.CouponDetailEntity_.couponNo.toString(), CriteriaUtil.Operator.IN, couponList)
        });
        QueryResult<CouponDetailEntity> qres = commonDao.findAll(CouponDetailEntity.class, CriteriaUtil.getCriteria(condition), null, null, null, null);
        if (qres == null || CollectionUtils.isEmpty(qres.getResultlist())) {
            return Collections.emptyList();
        } else {
            return qres.getResultlist();
        }
    }

    private List<CouponDetailEntity> findCouponByNo(List<String> couponList,String sta) throws Exception {
        L2RCondition condition = new L2RCondition();
        condition.setAndConditions(new ConditionDetail[]{
                new ConditionDetail(CouponDetailEntity.CouponDetailEntity_.couponNo.toString(), CriteriaUtil.Operator.IN, couponList),
                new ConditionDetail(CouponDetailEntity.CouponDetailEntity_.sta.toString(), CriteriaUtil.Operator.EQ, sta),
        });
        QueryResult<CouponDetailEntity> qres = commonDao.findAll(CouponDetailEntity.class, CriteriaUtil.getCriteria(condition), null, null, null, null);
        if (qres == null || CollectionUtils.isEmpty(qres.getResultlist())) {
            return Collections.emptyList();
        } else {
            return qres.getResultlist();
        }
    }
    @Override
    public CouponDetailEntity initNewCoupon(String couponCode, String lhotelGroupCode, String openid, String saleType, String fromUser) {
        CouponDetailEntity newCoupon = new CouponDetailEntity();
        newCoupon.setLhotelGroupCode(lhotelGroupCode);
        newCoupon.setOwnDate(new Date());
        newCoupon.setCouponCode(couponCode);
        newCoupon.setSta(CouponConstant.COUPON_STA.VALID);
        newCoupon.setOpenid(openid);
        newCoupon.setFromUser(fromUser);
        newCoupon.setFromDate(new Date());
        newCoupon.setSaleType(saleType);
        try {
            newCoupon.setCouponNo(this.generateNewCouponNo());
        } catch (Exception e) {
            throw new SysException(COUPON_ERROR, e);
        }
        return newCoupon;
    }

    /**
     * 查询可分享券
     *
     * @param couponPresentNo
     * @param numPerPart
     * @return
     * @throws Exception
     */
    private List<CouponPresentDetailEntity> findGivingCoupon(String couponPresentNo, Integer numPerPart) throws Exception {
        CouponPresentDetailEntity find = new CouponPresentDetailEntity();
        find.setPresentNo(couponPresentNo);
        find.setIsPresend(DefaultValue.F);
        QueryResult<CouponPresentDetailEntity> cList = commonDao.findAll(CouponPresentDetailEntity.class, CriteriaUtil.getCriteriaAllEQ(find), 1, numPerPart, null, null);
        if (cList == null || CollectionUtils.isEmpty(cList.getResultlist())) {
            return Collections.emptyList();
        } else {
            return cList.getResultlist();
        }
    }


    @Override
    public boolean hasPresentDrew(String openid, String couponPresentNo) throws Exception {
        CouponPresentDetailEntity find = new CouponPresentDetailEntity();
        find.setPresentNo(couponPresentNo);
        find.setToUser(openid);
        long count = commonDao.getCount(CouponPresentDetailEntity.class, CriteriaUtil.getCriteriaAllEQ(find), null);
        return count > 0;
    }

    @Override
    public CouponConsumeBaseEntity intiConsumeBase(String lhotelGroupCode, String goodCode, String couponCode, String memberNo, String openid) throws Exception {
        String consumeNo = generateCouponConsumeNo();
        CouponConsumeBaseEntity entity = new CouponConsumeBaseEntity();
        entity.setLhotelGroupCode(lhotelGroupCode);
        entity.setGoodCode(goodCode);
        entity.setCouponCode(couponCode);
        entity.setSta(CouponConsumeConstant.STA.INIT);
        entity.setConsumeNo(consumeNo);
        entity.setMemberNo(memberNo);
        entity.setOpenid(openid);
        return entity;
    }

    @Override
    @Transactional
    public void saveConsumeInfo(CouponConsumeBaseEntity baseEntity, List<CouponConsumeDetailEntity> details,List<CouponDetailEntity> updateCouponDetails) throws Exception {
        commonDao.save(baseEntity);
        commonDao.saveList(details);
        commonDao.mergeList(updateCouponDetails);
    }

    @Override
    public void sendResetPresentCouponMsg(String presentNo) {
        int s = (int) (PRESENT_RESET_DELAY * 60 * 60);
        CouponPresentResetParamDto paramDto = new CouponPresentResetParamDto();
        paramDto.setCouponPresentNo(presentNo);
        mnsUtil.putDelayMessageToQueue(QUEUE_RESET_PRESENT_COUPON, JacksonUtil.beanToJson(paramDto),s);
    }

    @Override
    @Transactional
    public void resetOresentCoupon(String presentNo) throws Exception {
        Lock lock = couponNoLock.obtain(presentNo);
        if (lock.tryLock(5, TimeUnit.SECONDS)) {
            try {
                CouponPresentBaseEntity findBase = new CouponPresentBaseEntity();
                findBase.setPresentNo(presentNo);
                findBase.setSta(CouponConstant.PRESEND_STA.STA_GIVING);
                CouponPresentBaseEntity presentBase = commonService.findOneEQ(CouponPresentBaseEntity.class, findBase);
                if(presentBase == null){return;}
                //更新赠送状态
                presentBase.setSta(CouponConstant.PRESEND_STA.STA_OVERDUE);
                CouponPresentDetailEntity findDetail = new CouponPresentDetailEntity();
                findDetail.setPresentNo(presentNo);
                QueryResult<CouponPresentDetailEntity> details = commonService.findAllEQ(CouponPresentDetailEntity.class, findDetail);
                List<String> couponDetailCodes = null;
                if(details != null ){
                    couponDetailCodes = details.getResultlist().stream()
                            .map(CouponPresentDetailEntity::getCouponNo)
                            .filter(StringUtil::isNotBlank)
                            .collect(Collectors.toList());
                }
                //需要更新的电子券
                List<CouponDetailEntity> updateCouponDetails = null;
                if(CollectionUtils.isNotEmpty(couponDetailCodes)){
                    updateCouponDetails = findCouponByNo(couponDetailCodes,CouponConstant.COUPON_STA.GIVING);
                    updateCouponDetails.stream()
                            .filter(Objects::nonNull)
                            .forEach(couponDetailEntity -> couponDetailEntity.setSta(CouponConstant.COUPON_STA.VALID));
                }
                if(CollectionUtils.isNotEmpty(updateCouponDetails)){
                    commonDao.mergeList(updateCouponDetails);
                }
                commonDao.merge(presentBase);
            }finally {
                lock.unlock();
            }

        }else {
            throw new SysException(COUPON_ERROR, "抢券人数太多,稍后重试.");
        }
    }

    @Override
    @Transactional
    public CouponConsumeDto couponConsum(CouponConsumeParamDto paramDto) throws Exception {
        String couponCode = paramDto.getCouponCode();
        L2RAssert.stringBlank(couponCode, "[couponCode] is null.");
        CouponBaseEntity couponBase = this.findCouponBaseByCode(couponCode);
        L2RAssert.isTrue(couponBase == null, new SysException(COUPON_ERROR, "没有 " + couponCode + "类型的券 "));
        String goodCode = paramDto.getGoodCode();
        String goodName;
        if (DefaultValue.F.equals(couponBase.getIsSpecify())) {
            L2RAssert.stringBlank(goodCode, "[goodCode] is null.");
            CouponGoodEntity couponGood = findCouponGoodByCouponCode(couponCode);
            L2RAssert.isTrue(couponGood == null, new SysException(COUPON_ERROR, "没有可以兑换的商品 "));
            goodCode = couponGood.getGoodCode();
            goodName = couponGood.getGoodName();
        } else {
            CouponGoodEntity couponGood = findCouponGoodByCouponCode(couponCode);
            L2RAssert.isTrue(couponGood == null, new SysException(COUPON_ERROR, "没有可以兑换的商品 "));
            goodCode = couponGood.getGoodCode();
            goodName = couponGood.getGoodName();
        }

        MemberSessionDto memberSession = ApiThreadLocal.getMemberSessionThreadLocal();
        String openid = memberSession.getOpenid();
        String memberNo = memberSession.getMemberNo();
        L2RAssert.isTrue(
                StringUtils.isBlank(openid) && StringUtils.isBlank(memberNo),
                new SysException(COUPON_ERROR, "session 不合法")
        );
        long count = countValidCouponByUser(couponCode, openid, memberNo);
        Integer amount = paramDto.getAmount();
        L2RAssert.isTrue(
                amount > count,
                new SysException(COUPON_ERROR, "当前有效券数量:" + count + "可用券数量不足. ")
        );
        CouponDetailEntity findCoupon = new CouponDetailEntity();
        findCoupon.setSta(CouponConstant.COUPON_STA.VALID);
        findCoupon.setCouponCode(couponCode);
        findCoupon.setOpenid(openid);
        findCoupon.setIsHalt(DefaultValue.F);
        QueryResult<CouponDetailEntity> qresDetail = commonService.findAllEQ(CouponDetailEntity.class, findCoupon, 1, amount);
        if (qresDetail == null || CollectionUtils.isEmpty(qresDetail.getResultlist())) {
            throw new SysException(COUPON_ERROR, "no coupon detail.");
        }

        //创建券消费记录
        CouponConsumeBaseEntity consumeBase = this.intiConsumeBase(paramDto.getLhotelGroupCode(), goodCode, couponCode, memberNo, openid);
        consumeBase.setAmount(amount);
        consumeBase.setGoodName(goodName);
        consumeBase.setSta(CouponConsumeConstant.STA.EXP);
        List<CouponConsumeDetailEntity> consumeDetails = new ArrayList<>();

        //修改券状态
        List<CouponDetailEntity> couponDetails = qresDetail.getResultlist();
        couponDetails.forEach(entity -> {
            entity.setSta(CouponConstant.COUPON_STA.USED);
            //创建consumeDetail
            CouponConsumeDetailEntity consumeDetail = new CouponConsumeDetailEntity();
            consumeDetail.setLhotelGroupCode(paramDto.getLhotelGroupCode());
            consumeDetail.setConsumeNo(consumeBase.getConsumeNo());
            consumeDetail.setCouponNo(entity.getCouponNo());
            consumeDetails.add(consumeDetail);
        });
        this.saveConsumeInfo(consumeBase, consumeDetails, couponDetails);
        return ClassConverUtil.copyProperties(consumeBase, CouponConsumeDto.class);
    }

    @Override
    public CouponConsumeTempDto couponConsumTemp(CouponConsumeParamDto paramDto) throws Exception {
        String couponCode = paramDto.getCouponCode();
        L2RAssert.stringBlank(couponCode, "[couponCode] is null.");
        CouponBaseEntity couponBase = this.findCouponBaseByCode(couponCode);
        L2RAssert.isTrue(couponBase == null, new SysException(COUPON_ERROR, "没有 " + couponCode + "类型的券 "));
        String goodCode = paramDto.getGoodCode();
        String goodName;
        if (DefaultValue.F.equals(couponBase.getIsSpecify())) {
            L2RAssert.stringBlank(goodCode, "[goodCode] is null.");
            CouponGoodEntity couponGood = findCouponGoodByCouponCode(couponCode);
            L2RAssert.isTrue(couponGood == null, new SysException(COUPON_ERROR, "没有可以兑换的商品 "));
            goodCode = couponGood.getGoodCode();
            goodName = couponGood.getGoodName();
        } else {
            CouponGoodEntity couponGood = findCouponGoodByCouponCode(couponCode);
            L2RAssert.isTrue(couponGood == null, new SysException(COUPON_ERROR, "没有可以兑换的商品 "));
            goodCode = couponGood.getGoodCode();
            goodName = couponGood.getGoodName();
        }

        MemberSessionDto memberSession = ApiThreadLocal.getMemberSessionThreadLocal();
        String openid = memberSession.getOpenid();
        String memberNo = memberSession.getMemberNo();
        L2RAssert.isTrue(
                StringUtils.isBlank(openid) && StringUtils.isBlank(memberNo),
                new SysException(COUPON_ERROR, "session 不合法")
        );
        long count = countValidCouponByUser(couponCode, openid, memberNo);
        Integer amount = paramDto.getAmount();
        L2RAssert.isTrue(
                amount > count,
                new SysException(COUPON_ERROR, "当前有效券数量:" + count + "可用券数量不足. ")
        );
        CouponDetailEntity findCoupon = new CouponDetailEntity();
        findCoupon.setSta(CouponConstant.COUPON_STA.VALID);
        findCoupon.setCouponCode(couponCode);
        findCoupon.setOpenid(openid);
        findCoupon.setIsHalt(DefaultValue.F);
        QueryResult<CouponDetailEntity> qresDetail = commonService.findAllEQ(CouponDetailEntity.class, findCoupon, 1, amount);
        if (qresDetail == null || CollectionUtils.isEmpty(qresDetail.getResultlist())) {
            throw new SysException(COUPON_ERROR, "no coupon detail.");
        }

        //创建券消费记录
        CouponConsumeBaseEntity consumeBase = this.intiConsumeBase(paramDto.getLhotelGroupCode(), goodCode, couponCode, memberNo, openid);
        consumeBase.setAmount(amount);
        consumeBase.setGoodName(goodName);
        consumeBase.setSta(CouponConsumeConstant.STA.EXP);
        List<CouponConsumeDetailEntity> consumeDetails = new ArrayList<>();

        //修改券状态
        List<CouponDetailEntity> couponDetails = qresDetail.getResultlist();
        couponDetails.forEach(entity -> {
            entity.setSta(CouponConstant.COUPON_STA.USED);
            //创建consumeDetail
            CouponConsumeDetailEntity consumeDetail = new CouponConsumeDetailEntity();
            consumeDetail.setLhotelGroupCode(paramDto.getLhotelGroupCode());
            consumeDetail.setConsumeNo(consumeBase.getConsumeNo());
            consumeDetail.setCouponNo(entity.getCouponNo());
            consumeDetails.add(consumeDetail);
        });
        CouponConsumeTempDto res = new CouponConsumeTempDto();
        res.setBaseEntity(consumeBase);
        res.setUpdateCouponDetails(couponDetails);
        res.setDetails(consumeDetails);
        return res;
    }


    @Override
    public Long findCouponCount(String lhotelGroupCode, String couponCode,String openid) throws Exception {
        CouponDetailEntity find = new CouponDetailEntity();
        find.setLhotelGroupCode(lhotelGroupCode);
        find.setCouponCode(couponCode);
        find.setOpenid(openid);
        find.setSta(CouponConstant.COUPON_STA.VALID);
        find.setIsHalt(DefaultValue.F);
        return commonService.getCountAllEQ(CouponDetailEntity.class, find, null);
    }

    private long countValidCouponByUser(String couponCode, String openid, String memberNo) throws Exception {
        CouponDetailEntity find = new CouponDetailEntity();
        find.setOpenid(openid);
        find.setCouponCode(couponCode);
        find.setSta(CouponConstant.COUPON_STA.VALID);
        return commonService.getCountAllEQ(CouponDetailEntity.class, find, null);
    }

    private String generateCouponConsumeNo() throws Exception {
        return callProcedure(couponConsumLocLkey);
    }
    private CouponGoodEntity findCouponGoodByCouponCode(String couponCode) throws Exception {
        CouponGoodEntity find = new CouponGoodEntity();
        find.setCouponCode(couponCode);
        find.setIsHalt(DefaultValue.F);
        return commonService.findOneEQ(CouponGoodEntity.class, find);


    }
    private CouponBaseEntity findCouponBaseByCode(String code) throws Exception {
        CouponBaseEntity find = new CouponBaseEntity();
        find.setCode(code);
        return commonService.findOneEQ(CouponBaseEntity.class, find);
    }

    private String callProcedure(String lockKey) throws Exception {
        Lock lock = couponNoLock.obtain(lockKey);
        if (lock.tryLock(2, TimeUnit.SECONDS)) {
            try {
                List params = new ArrayList<>();
                params.add(lockKey);
                String no = commonService.findOneFieldByProcedure("create_No", params);
                return no;
            } finally {
                lock.unlock();
            }
        } else {
            throw new SysException(COUPON_ERROR, "生成" + lockKey + "异常,稍后重试");
        }
    }

	@Override
	public Long findCouponCountAll(String lhotelGroupCode, String couponCode, String openid) throws Exception {
		CouponDetailEntity find = new CouponDetailEntity();
        find.setLhotelGroupCode(lhotelGroupCode);
        find.setCouponCode(couponCode);
        find.setOpenid(openid);
        return commonService.getCountAllEQ(CouponDetailEntity.class, find, null);
	}

	@Override
	public void coupenCodeCollarCoupen(String lhotelGroupCode, String couponCode, String couponCodeType) {
		// TODO Auto-generated method stub
		
	}
}
